package com.phpxiu.app.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.google.android.gms.plus.PlusShare;
import com.phpxiu.app.api.callback.OnRequestShareCallback;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.download.PicDownloadCallBack;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.kkylive.WBShareActivity;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.ShareContent;
import com.phpxiu.app.supports.qq.QQShareContent;
import com.phpxiu.app.supports.qq.TManager;
import com.phpxiu.app.supports.qq.ZoneShareContent;
import com.phpxiu.app.utils.KKYUtil;
import com.tencent.bugly.imsdk.crashreport.CrashReport;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.tweetcomposer.TweetComposer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import io.fabric.sdk.android.Fabric;

/**
 * @file
 * @brief 基本分享封装
 * @author 吴金洲
 * @note 基本分享封装，封装了分享到第三方平台的一些实现逻辑
 *
 */
public class BaseShare extends UIBase implements OnRequestShareCallback {
    public final static String TAG="BaseShare";
    public final static int PLATFORM_FB=0x1;//facebook平台
    public final static int PLATFORM_TT=0x2;//twitter平台
    public final static int PLATFORM_INS=0x3;//instagram平台
    public final static int PLATFORM_GG=0x4;//google+平台
    public final static int PLATFORM_WX=0x5;//微信好友
    public final static int PLATFORM_WF=0x6;//微信朋友圈
    public final static int PLATFORM_WB=0x7;//新浪微博
    public final static int PLATFORM_QQ=0x8;//QQ好友
    public final static int PLATFORM_QZ=0x9;//QQ空间

    public final static int REQUEST_WB_SHARE_CODE=0x111;//分享到新浪微博请求
    public final static int REQUEST_TW_SHARE_CODE=0x112;//分享到twitter请求
    public final static int REQUEST_INS_SHARE_CODE=0x113;//分享到Instagram请求
    public final static int REQUEST_GOOGLE_SHARE_CODE=0x114;//分享到Google请求

    private ImagePipeline mPipeline = Fresco.getImagePipeline();
    private ImageRequest mImageRequest =null;
    private DataSource<CloseableReference<CloseableImage>> bitmapSource;

    private ShareDialog faceBookShare;//分享到facebook
    private CallbackManager fbManager;
    private boolean isRequestingShare=false;//请求连接分享中

    private static Tencent mQQ;
    private static IWXAPI mWXApi;
    private boolean isShareToWeiXin=true;

    private ShareContent mBaseShareContent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fabric.with(this, new TwitterCore(BaseLogin.T_CONFIG), new TweetComposer());
        if(mQQ==null){
            mQQ= KKYApp.getInstance().mQQ;
        }
        if(mWXApi==null){
            mWXApi= KKYApp.getInstance().mWeiXinAPI;
        }
    }

    /**
     * 分享到某个平台
     */
    @Override
    public void onRequestShareContentTo(int platform,ShareContent shareContent){
        if(isRequestingShare||shareContent==null){
            return;
        }
        mBaseShareContent=shareContent;

        switch (platform){
            case PLATFORM_FB:
                shareToFacebook();
                break;
            case PLATFORM_TT:
                shareToTwitter();
                break;
            case PLATFORM_INS:
                shareToIns();
                break;
            case PLATFORM_GG:
                shareToGoogle();
                break;
            case PLATFORM_WX:
                shareToWX(true);
                break;
            case PLATFORM_WF:
                shareToWX(false);
                break;
            case PLATFORM_WB:
                shareToWB();
                break;
            case PLATFORM_QQ:
                shareToQQ();
                break;
            case PLATFORM_QZ:
                shareToQZ();
                break;
            default:
                break;
        }
    }

    /**
     * 分享到facebook
     */
    final private void shareToFacebook(){
        if(mBaseShareContent==null){
            return;
        }
        if(faceBookShare==null){
            //LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
            faceBookShare = new ShareDialog(this);
            fbManager= CallbackManager.Factory.create();
            faceBookShare.registerCallback(fbManager,new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    onPlatformShareBack(PLATFORM_FB);
                }

                @Override
                public void onCancel() {
                    onPlatformShareBack(PLATFORM_FB);
                }

                @Override
                public void onError(FacebookException e) {
                    onPlatformShareBack(PLATFORM_FB);
                }
            });
        }
        try {
            ShareLinkContent linkContent = new ShareLinkContent.Builder()
                    .setContentTitle(mBaseShareContent.getTitle())
                    .setContentDescription(mBaseShareContent.getSummary())
                    .setContentUrl(Uri.parse(mBaseShareContent.getTargetUrl()))
                    .setImageUrl(Uri.parse(mBaseShareContent.getImageUrl()))
                    .build();
            if(faceBookShare.canShow(ShareLinkContent.class)){
                faceBookShare.show(this,linkContent);
                isRequestingShare=true;
            }
            isRequestingShare=true;
        }catch (Exception e){
            if(KKYUtil.DEBUG){
                Toast.makeText(this,"facebook share content exception!",Toast.LENGTH_LONG).show();
            }
            e.printStackTrace();
        }
    }

    /**
     * 分享本地文件，如微信、twitter、instagram和google等
     * @param platform
     */
    final private void shareLocalFile(int platform){
        mImageRequest= ImageRequestBuilder.newBuilderWithSource(Uri.parse(mBaseShareContent.getImageUrl())).setProgressiveRenderingEnabled(true).build();
        bitmapSource=mPipeline.fetchDecodedImage(mImageRequest,this);
        bitmapSource.subscribe(new ShareImageData(platform), CallerThreadExecutor.getInstance());
        isRequestingShare=true;
    }

    /**
     * 分享到facebook
     */
    final private void shareToTwitter(){
        shareLocalFile(PLATFORM_TT);
    }

    /**
     * 分享到Instagram
     */
    final private void shareToIns(){
        shareLocalFile(PLATFORM_INS);
    }

    /**
     * 分享到google+
     */
    final private void shareToGoogle(){
        shareLocalFile(PLATFORM_GG);
    }

    /**
     * 分享到微信平台
     * @param isWeiXin true分享到微信好友 false分享到微信朋友圈
     */
    final private void shareToWX(boolean isWeiXin){
        isShareToWeiXin=isWeiXin;
        shareLocalFile(PLATFORM_WX);
    }

    /**
     * 分享到新浪微博
     */
    final private void shareToWB(){
        if(!KKYApp.mSinaShareAPI.isWeiboAppInstalled()){
            Toast.makeText(this, getString(R.string.login_sina_not_install), Toast.LENGTH_LONG).show();
            return;
        }
        Intent shareToSina = new Intent(BaseShare.this, WBShareActivity.class);
        shareToSina.putExtra(WBShareActivity.TITLE, mBaseShareContent.get_title());
        shareToSina.putExtra(WBShareActivity.IMAGE, mBaseShareContent.getImageUrl());
        shareToSina.putExtra(WBShareActivity.URL,mBaseShareContent.getTargetUrl());
        startActivityForResult(shareToSina,REQUEST_WB_SHARE_CODE);
        isRequestingShare=true;
    }

    /**
     * 分享到QQ
     */
    final private void shareToQQ(){
        final QQShareContent qsc=new QQShareContent(mBaseShareContent.getTitle()+"",mBaseShareContent.getTargetUrl(),getString(R.string.app_name));
        qsc.setSummary(mBaseShareContent.getSummary());
        qsc.setImageUrl(mBaseShareContent.getImageUrl());
        TManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mQQ.shareToQQ(BaseShare.this,qsc.content,QQShareListener);
                isRequestingShare=true;
            }
        });
    }

    /**
     * 分享到QQ空间
     */
    final private void shareToQZ(){
        final ZoneShareContent qsc=new ZoneShareContent(mBaseShareContent.getTitle()+"",mBaseShareContent.getTargetUrl());
        qsc.setSummary(mBaseShareContent.getSummary());
        qsc.setImageUrl(mBaseShareContent.getImageUrl());
        TManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mQQ.shareToQzone(BaseShare.this, qsc.content, QQShareListener);
                isRequestingShare=true;
            }
        });
    }

    /**
     * 平台分享返回，取消、异常或分享完成返回时调用
     * @param platform 平台
     */
    protected void onPlatformShareBack(int platform){
        isRequestingShare=false;
    }

    /**
     * bitmap转化成流
     */
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(KKYUtil.DEBUG){
            Toast.makeText(this,"Share requestCode="+requestCode,Toast.LENGTH_LONG).show();
        }
        if(requestCode==REQUEST_WB_SHARE_CODE){
            onPlatformShareBack(PLATFORM_WB);
        }else if(requestCode==REQUEST_TW_SHARE_CODE){
            onPlatformShareBack(PLATFORM_TT);
            if(KKYUtil.DEBUG){
                Toast.makeText(this,"twitter back",Toast.LENGTH_LONG).show();
            }
        }else if(requestCode==REQUEST_INS_SHARE_CODE){
            onPlatformShareBack(PLATFORM_INS);
        }else if(requestCode==REQUEST_GOOGLE_SHARE_CODE){
            onPlatformShareBack(PLATFORM_GG);
        }else if(requestCode == Constants.REQUEST_QQ_SHARE||requestCode == Constants.REQUEST_QZONE_SHARE){
            Tencent.onActivityResultData(requestCode, resultCode, data, QQShareListener);
        }else{
            fbManager.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void finish() {
        mBaseShareContent=null;
        super.finish();
    }

    @Override
    protected void onDestroy() {
        mBaseShareContent=null;
        super.onDestroy();
    }

    /**
     * QQ QQ空间分享回调
     */
    private IUiListener QQShareListener=new IUiListener() {
        @Override
        public void onComplete(Object response) {
            onPlatformShareBack(PLATFORM_QQ);
        }

        @Override
        public void onError(UiError uiError) {
            onPlatformShareBack(PLATFORM_QQ);
        }

        @Override
        public void onCancel() {
            onPlatformShareBack(PLATFORM_QQ);
        }
    };

    private class  ShareImageData extends BaseBitmapDataSubscriber {
        private final static String TYPE="image/*";
        private int platform;//分享到的平台
        private ShareImageData(int platform) {
            this.platform = platform;
        }

        @Override
        protected void onNewResultImpl(Bitmap bitmap) {
            if(bitmap==null||mBaseShareContent==null){
                onPlatformShareBack(platform);
                return;
            }
            if(PLATFORM_TT==platform||PLATFORM_INS==platform||PLATFORM_GG==platform){
                File cache=new File(PicDownloadCallBack.PIC_CACHE);
                if(!cache.exists()){
                    cache.mkdirs();
                }
                File mFile=new File(PicDownloadCallBack.PIC_CACHE,"share_pic"+ MySelfInfo.getInstance().getId()+".jpg");
                FileOutputStream out =null;
                try {
                    out = new FileOutputStream(mFile);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                    out.flush();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    onPlatformShareBack(platform);
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                    onPlatformShareBack(platform);
                    return;
                }finally {
                    if(out!=null){
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }

                if(PLATFORM_TT==platform){
                    //TweetComposer.Builder builder = null;
                    try {
                        /**
                        builder = new TweetComposer.Builder(BaseShare.this)
                                .text(mBaseShareContent.getSummary())
                                .url(new URL(mBaseShareContent.getTargetUrl()))
                                .image(Uri.fromFile(mFile));
                        builder.show();
                         **/
                        Intent tt = new TweetComposer.Builder(BaseShare.this)
                                .text(mBaseShareContent.getSummary())
                                .url(new URL(mBaseShareContent.getTargetUrl()))
                                .image(Uri.fromFile(mFile))
                                .createIntent();
                        startActivityForResult(tt,REQUEST_TW_SHARE_CODE);
                    } catch (MalformedURLException e) {
                        onPlatformShareBack(platform);
                        e.printStackTrace();
                    }
                }else if(PLATFORM_INS==platform){
                    Intent share = new Intent(Intent.ACTION_SEND);
                    share.setType(TYPE);
                    Uri uri = Uri.fromFile(mFile);
                    share.putExtra(Intent.EXTRA_STREAM, uri);
                    startActivityForResult(Intent.createChooser(share, getString(R.string.system_share_title)),REQUEST_INS_SHARE_CODE);
                }else if(PLATFORM_GG==platform){
                    try {
                        Uri uri = Uri.fromFile(mFile);
                        PlusShare.Builder share = new PlusShare.Builder(BaseShare.this);
                        String text=mBaseShareContent.getTitle()+"\\n"+mBaseShareContent.getSummary()+ HttpConfig.SHARE_URL+ MySelfInfo.getInstance().getId();
                        share.setText(text);
                        share.addStream(uri);
                        share.setType(TYPE);
                        startActivityForResult(share.getIntent(),REQUEST_GOOGLE_SHARE_CODE);
                    }catch (Exception e){
                        onPlatformShareBack(platform);
                        CrashReport.postCatchedException(e);
                        if(KKYUtil.DEBUG){
                            Toast.makeText(BaseShare.this,"Share Failed:Not install G+ or file is invalid!",Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }

            if(PLATFORM_WX==platform){
                WXWebpageObject localWXWebObject = new WXWebpageObject();
                localWXWebObject.webpageUrl= HttpConfig.SHARE_URL+ MySelfInfo.getInstance().getId();
                //设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
                WXMediaMessage msg=new WXMediaMessage(localWXWebObject);
                msg.title=mBaseShareContent.getTitle();
                msg.description=mBaseShareContent.getSummary();
                Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
                msg.thumbData=bmpToByteArray(thumbBmp,true);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                if(isShareToWeiXin){
                    req.scene= SendMessageToWX.Req.WXSceneSession;//分享到微信好友
                }else{
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈
                }
                mWXApi.sendReq(req);
            }

        }

        @Override
        protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> closeableReferenceDataSource) {
            onPlatformShareBack(platform);
        }
    }
}
